import pickle
import os
import sys
from os import system
from datetime import date, datetime
import select
def timeoutable_input(clue="", timeout=None):
    print(clue, end="")
    i, o, e = select.select([sys.stdin], [], [], timeout)
    if i:
        return sys.stdin.readline().rstrip('\n')
    return None


class Task():
    def __init__(self, discribe, father) -> None:
        self.describe = discribe
        self.father = father
        self.start_time = datetime.now()
        # 子任务
        self.child_task = {}

    def end(self):
        self.end_time = datetime.now()
        self.cost = self.end_time - self.start_time
        


def main():
    if os.path.exists("xbr.data"):
        with open("xbr.data", "rb") as f:
            usr_data = pickle.load(f)
    else:
        with open("xbr.data", "wb") as f:
            usr_data = {
                "随手记": {},
                "事件": {},
                "任务": {}
            }
            pickle.dump(usr_data, f)
    TIMEKEEPING = {}
    show_task = None
    while True:
        mode = 0
        str_show = f"当前时间：{datetime.now()}\n"
        if show_task:
            str_show += f"当前场景：{show_task.father.describe if show_task.father else ""}\n"
            str_show += f"耗时：{datetime.now() - show_task.father.start_time if show_task.father else ""}\n"
            str_show += f"    当前任务：{show_task.describe}\n"
            str_show += f"    耗时：{datetime.now() - show_task.start_time}\n"
        str_show += "1. 随手记\n"
        str_show += "2. 开始计时\n"
        str_show += "3. 停止计时\n"
        str_show += "4. 撤销该计时\n"
        str_show += "5. 结束本次计时\n"
        system ("clear")
        print(str_show)
        mode = timeoutable_input(timeout=3)
        if mode == '1':
            thinking = {}
            thinking['time'] = datetime.now()
            task = input("请输入想法：")
            usr_data['随手记'][task] = thinking
            print(usr_data)
            input()
            with open("xbr.data", "wb") as f:
                pickle.dump(usr_data, f)
        if mode == '2':
            task_describe = input("事件：")
            show_task = Task(task_describe, show_task)
        if mode == '3':
            show_task.end()
            if show_task.describe in usr_data["事件"]:
                usr_data["事件"][show_task.describe].append(show_task)
            else:
                usr_data["事件"][show_task.describe]=[show_task]
            show_task = show_task.father
            with open("xbr.data", "wb") as f:
                pickle.dump(usr_data, f)
        if mode == '4':
            show_task = show_task.father
        if mode == '5':
            break


if __name__ == "__main__":
    main()
